package com.financing.platform.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.financing.platform.common.CsvExportable;
import com.financing.platform.dto.FpFaOfflineUserDTO;

/**
 * 导出Csv 工具类
 * @author lisu
 *
 */
public class CsvExportUtil {

	protected static Logger log = Logger.getLogger(CsvExportUtil.class);

	/**
	 * Export records to csv file
	 * 
	 * @param response
	 *            Http response
	 * @param items
	 *            List of item that implements on CsvExportable interface
	 * @throws IOException
	 */
	public static void doCsvExport(HttpServletResponse response,
			List<CsvExportable> items) throws IOException {
		// reset response buffer and header information
		log.info("in doCsvExport results to csv");
		response.reset();
		response.setHeader("Content-Disposition",
				"attachment;filename=export.csv");
		OutputStreamWriter osw = null;
		try {
			osw = new OutputStreamWriter(response.getOutputStream(), "GB2312"); 
			// csv bom 
			osw.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));  
			for (int i = 0; i < items.size(); i++) {
				CsvExportable item = items.get(i);
				
				if (i == 0) {
					osw.write(item.csvTitle());
					osw.write("\r\n");
				}
				osw.write(item.toCsvString());
				osw.write("\r\n");
				if ((i + 1) % 100 == 0) {
					osw.flush();  
				}
				
			}
		} catch (IOException e) {
			log.error("Exception happens when export results to csv", e);
			throw e;
		} finally {
			if (osw != null) {
				osw.close();
			}
		}
	}
	
	public static void doCsvExportForZip(ZipOutputStream zipOutputStream,
			List<CsvExportable> items, String zipEntryName) throws IOException {
		log.info("in doCsvExportForZip results to csvZip");
		try {
			
			ZipEntry zipEntry = new ZipEntry(zipEntryName);

			zipOutputStream.putNextEntry(zipEntry);
			// csv bom
			zipOutputStream.write(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF });
			for (int i = 0; i < items.size(); i++) {

				CsvExportable item = items.get(i);

				if (i == 0) {
					zipOutputStream.write(item.csvTitle().getBytes("GB2312"));
					zipOutputStream.write("\r\n".getBytes("GB2312"));
				}
				zipOutputStream.write(item.toCsvString().getBytes("GB2312"));
				zipOutputStream.write("\r\n".getBytes("GB2312"));
				if ((i + 1) % 100 == 0) {
					zipOutputStream.flush();
				}

			}
		} catch (IOException e) {
			log.error("Exception happens when export results to csv", e);
			throw e;
		} 
	}
	
	
	public static List<FpFaOfflineUserDTO> doCsvImportOfflineUser(String path)throws IOException{
		log.info("in doCsvImportOfflineUser ");
		try {
			
			 File csv = new File(path); 
			 List<String> readLines = IOUtils.readLines(new FileInputStream(csv),"GB2312");
			 List<FpFaOfflineUserDTO> list =  new ArrayList<FpFaOfflineUserDTO>();
			 for (int i = 0; i < readLines.size(); i++) {
				//模板固定  - 前两行 不做处理 
				if(i<1){
					continue;
				}
				String string = readLines.get(i);
				// 把一行数据分割成多个字段 
				String[] st = string.split(",");
				
				//手机号为不做处理
				if(StringUtils.isBlank(st.length>=2?st[1]:null)){
					continue;
				}
				
				FpFaOfflineUserDTO bean = new FpFaOfflineUserDTO();
				bean.setNumber(st.length>=1?st[0]:null);
				bean.setMobile(st.length>=2?st[1]:null);
				bean.setName(st.length>=3?st[2]:null);
				bean.setJob(st.length>=4?st[3]:null);
				if("男".equals(st.length>=5?st[4]:null)){
					bean.setSex(1);
				}else
				if("女".equals(st.length>=5?st[4]:null)){
					bean.setSex(2);
				}
				bean.setCompanyName(st.length>=6?st[5]:null);
				bean.setCompanyAdd(st.length>=7?st[6]:null);
				bean.setCompanyWebsite(st.length>=8?st[7]:null);
				bean.setEmail(st.length>=9?st[8]:null);
				bean.setWeChat(st.length>=10?st[9]:null);
				bean.setMediaSource(st.length>=11?st[10]:null);
				bean.setRemark(st.length>=12?st[11]:null);
				list.add(bean);		
			}
			 return list;
		} catch (IOException e) {
			log.error("Exception happens when export results to csv", e);
			throw e;
		} 
	}
	public static List<FpFaOfflineUserDTO> doXlsImportOfflineUser(String path,Boolean isOss)throws Exception{
		log.info("in doXlsImportOfflineUser ");
		List<FpFaOfflineUserDTO> list =  new ArrayList<FpFaOfflineUserDTO>();
		try{
			InputStream fis = null;
			if(!isOss) {
				File file = new File(path);
				fis = new FileInputStream(file);
			}else{
				fis = AliyunOssUtil.readFile(path.substring(1,path.length()));
			}

			jxl.Workbook rwb = Workbook.getWorkbook(fis);

			Sheet[] sheet = rwb.getSheets();
			for (int i = 0; i < sheet.length; i++) {
				Sheet rs = rwb.getSheet(i);
				for (int j = 1; j < rs.getRows(); j++) {
					Cell[] st = rs.getRow(j);

					//手机号为不做处理
					if(StringUtils.isBlank(st.length>=2?st[1].getContents():null)){
						break;
					}

					FpFaOfflineUserDTO bean = new FpFaOfflineUserDTO();
					bean.setNumber(st.length>=1?st[0].getContents():null);
					bean.setMobile(st.length>=2?st[1].getContents():null);
					bean.setName(st.length>=3?st[2].getContents():null);
					bean.setJob(st.length>=4?st[3].getContents():null);
					if("男".equals(st.length>=5?st[4].getContents():null)){
						bean.setSex(1);
					}else
					if("女".equals(st.length>=5?st[4].getContents():null)){
						bean.setSex(2);
					}
					bean.setCompanyName(st.length>=6?st[5].getContents():null);
					bean.setCompanyAdd(st.length>=7?st[6].getContents():null);
					bean.setCompanyWebsite(st.length>=8?st[7].getContents():null);
					bean.setEmail(st.length>=9?st[8].getContents():null);
					bean.setWeChat(st.length>=10?st[9].getContents():null);
					bean.setMediaSource(st.length>=11?st[10].getContents():null);
					bean.setRemark(st.length>=12?st[11].getContents():null);
					list.add(bean);

				}

			}

			fis.close();
			rwb.close();
		}catch(Exception e){
			log.error("ExceptiondoXlsImportOfflineUser to xls", e);
			throw e;
		}
		return list;

	}
	public static List<FpFaOfflineUserDTO> doXlsImportOfflineUser(String path)throws Exception{
		return doXlsImportOfflineUser(path,false);
	}
}
